package org.hepeng.workx.mybatis.session;

import org.apache.ibatis.session.SqlSession;
import org.hepeng.workx.mybatis.executor.SQLExecuteContext;
import org.hepeng.workx.util.proxy.Invocation;
import org.hepeng.workx.util.proxy.Invoker;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author he peng
 */
public class AttributeSqlSessionWrapper implements Invoker {

    private Map<String , Object> attributes = new ConcurrentHashMap<>();
    private SqlSession sqlSession;

    public AttributeSqlSessionWrapper(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Invocation invocation) throws Throwable {
        SQLExecuteContext context = SQLExecuteContext.getContext();
        context.putAll(attributes);
        Method method = invocation.getMethod();
        return method.invoke(this.sqlSession , invocation.getArgs());
    }

    public void setMapperInterface(Class<?> mapperInterface) {
        if (Objects.nonNull(mapperInterface)) {
            attributes.put("mapperInterface" , mapperInterface);
        }
    }
}
